
/*
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */


#include <stdio.h>

#include "libmooigraph.h"
#include "lmg.h"


static void lmg_split1edge (struct lmgedgel *el);
static void lmg_eqlevel (struct lmgedgel *el);

void
lmg_splitedges (void)
{
  struct lmgedgel *eptr;
  struct lmgedgel *eptr2;
  struct lmgnode *tmp;
  if (lmgdebug)
    {
      printf ("%s(): start\n", __FUNCTION__);
    }
  eptr = lmgedgelist;
  while (eptr)
    {
      eptr2 = eptr->next;
      if (eptr->edge->to->tree_layout.level -
	  eptr->edge->from->tree_layout.level == 0)
	{
	  lmg_eqlevel (eptr);
	}
      eptr = eptr2;
    }
  eptr = lmgedgelist;
  while (eptr)
    {
      eptr2 = eptr->next;
      if (eptr->edge->to->tree_layout.level -
	  eptr->edge->from->tree_layout.level < 0)
	{
	  tmp = eptr->edge->from;
	  eptr->edge->from = eptr->edge->to;
	  eptr->edge->to = tmp;
	  if (eptr->edge->bitflags.reversed)
	    {
	      eptr->edge->bitflags.reversed = 0;
	    }
	  else
	    {
	      eptr->edge->bitflags.reversed = 1;
	    }
	}

      if (eptr->edge->to->tree_layout.level -
	  eptr->edge->from->tree_layout.level > 1)
	{
	  lmg_split1edge (eptr);
	}
      eptr = eptr2;
    }
  if (lmgdebug)
    {
      printf ("%s(): finish\n", __FUNCTION__);
    }
  return;
}

static void
lmg_split1edge (struct lmgedgel *el)
{
  struct lmgnode *sn;
  struct lmgnode *en;
  struct lmgnode *prev;
  struct lmgnodel *d1;
  int len;
  int i;
  sn = el->edge->from;
  en = el->edge->to;
  len = en->tree_layout.level - sn->tree_layout.level;
  prev = sn;
  for (i = 1; i < len; i++)
    {
      d1 = lmg_dummynode ();
      d1->node->tree_layout.level = prev->tree_layout.level + 1;
      lmg_edgelistadd (prev, d1->node, el->edge->color, el->edge->style);
      prev = d1->node;
    }
  lmg_edgelistadd (prev, en, el->edge->color, el->edge->style);
  lmg_deledge (el);
  return;
}

static void
lmg_eqlevel (struct lmgedgel *el)
{
  struct lmgnode *sn;
  struct lmgnode *en;
  struct lmgnodel *d1;
  int level;
  sn = el->edge->from;
  en = el->edge->to;
  level = en->tree_layout.level;
  d1 = lmg_dummynode ();
  d1->node->tree_layout.level = level + 1;
  lmg_edgelistadd (sn, d1->node, el->edge->color, el->edge->style);
  lmg_edgelistadd (d1->node, en, el->edge->color, el->edge->style);
  lmg_deledge (el);
  return;
}

/* End */
